import json
import os
from collections import defaultdict
from datetime import datetime, timedelta,time as dtime
import configparser
CONFIG_FILE = 'config.ini'
# 转换规则字典
#CONVERSION_RULE = {10: 5, 5: 10, 1: 6, 6: 1, 2: 7, 7: 2, 3: 8, 8: 3, 4: 9, 9: 4}
CONVERSION_RULE = {0:9,1:3,2:5,3:7,4:1,5:9}

def save_settings(total_num,win_cnt):
        config = configparser.ConfigParser()
        config.read(CONFIG_FILE)
        # 创建配置部分
        config['SETTINGS'] = {
            'total_money': config.get('SETTINGS', 'total_money', fallback='5000'),
            'init_money': config.get('SETTINGS', 'init_money', fallback='2'),
            'run_time': config.get('SETTINGS', 'run_time', fallback='24'),
            'ip': config.get('SETTINGS', 'ip', fallback='c145902.sys998.com'),
            'cookie_value': config.get('SETTINGS', 'cookie_value', fallback=''),
            'refresh_time': config.get('SETTINGS', 'refresh_time', fallback='180'),
            'trigger_count': config.get('SETTINGS', 'trigger_count', fallback='1'),
            'profit_money': config.get('SETTINGS', 'profit_money', fallback='5000'),
            'choose_number': config.get('SETTINGS', 'choose_number', fallback='0:9,1:3,2:5,3:7,4:1,5:9'),
            'start_count': config.get('SETTINGS', 'start_count', fallback='20'),
            'total_num': str(total_num),
            'win_cnt': str(win_cnt),
            'right_now': config.get('SETTINGS', 'right_now', fallback='0'),
            'direct': config.get('SETTINGS', 'direct', fallback='<'),
            'jsq': config.get('SETTINGS', 'jsq', fallback='2.5'),
            'jsqzy': config.get('SETTINGS', 'jsqzy', fallback=''),
            'cai_start': config.get('SETTINGS', 'cai_start', fallback='9'),
            'cai_end': config.get('SETTINGS', 'cai_end', fallback='9')
        }
        # 写入配置文件
        with open(CONFIG_FILE, 'w') as configfile:
            config.write(configfile)


def parse_date(time_str):
    """解析时间字符串为日期对象"""
    return datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S").date()


def convert_numbers(numbers):
    """根据规则转换号码列表"""
    return [CONVERSION_RULE.get(n, n) for n in numbers]


def group_data_by_date(data):
    """按上一天CYCLE_START_HOUR点到下一天CYCLE_END_HOUR点作为一个周期分组数据并按期号升序排列"""
    daily_data = defaultdict(list)
    for item in data['items']:
        open_time = datetime.strptime(item['open_time'], "%Y-%m-%d %H:%M:%S")

        # 计算周期的起始和结束时间点
        if open_time.hour >= int(cai_start1):
            # 开奖时间在起始小时之后，周期起始为当天
            cycle_start_date = open_time.date()
        else:
            # 开奖时间在起始小时之前，周期起始为前一天
            cycle_start_date = open_time.date() - timedelta(days=1)

        # 计算周期起始和结束的完整时间
        cycle_start = datetime.combine(cycle_start_date, datetime.min.time()) + timedelta(hours=int(cai_start1))
        cycle_end = cycle_start + timedelta(days=1)

        # 处理特殊的24点情况
        if int(cai_end1) != 24:
            cycle_end = datetime.combine(cycle_start_date + timedelta(days=1), datetime.min.time()) + timedelta(
                hours=int(cai_end1))

        # 确定当前开奖时间属于哪个周期（以周期结束日期作为周期标识）
        if cycle_start <= open_time < cycle_end:
            cycle_date = cycle_start_date + timedelta(days=1)
        else:
            # 处理边界情况
            if open_time >= cycle_end:
                cycle_date = cycle_start_date + timedelta(days=2)
            else:
                cycle_date = cycle_start_date + timedelta(days=1)

        daily_data[cycle_date].append(item)
    
    today_str = str(datetime.now().strftime( "%Y-%m-%d %H:%M:%S"))
    today = datetime.strptime(today_str, "%Y-%m-%d %H:%M:%S")
    next_today = datetime.combine(today + timedelta(days=1), datetime.min.time()) + timedelta(
                hours=int(cai_end1) )
    today_today = datetime.combine(today, datetime.min.time()) + timedelta(
                hours=int(cai_start1))
    if daily_data[next_today.date()]:
        next_data = daily_data[next_today.date()]
        for item in next_data:
             open_time1 = datetime.strptime(item['open_time'], "%Y-%m-%d %H:%M:%S")
             if today_today <= open_time1 < next_today:
                daily_data[today.date()].append(item)


    # 对每天的数据按期号升序排列
    for date in daily_data:
        daily_data[date] = sorted(daily_data[date], key=lambda x: int(x['issue_no']))

    return daily_data
def can_afford_bet(current_capital, base_bet_amount, total_bet_numbers):
    """检查当前本金是否足够支付一组投注（总投注金额=单注金额×总押注号码数）"""
    return current_capital >= base_bet_amount * total_bet_numbers

def analyze_daily_data(daily_items):
    """分析单日数据，生成当前期与下期的中奖统计"""
    sorted_items = sorted(daily_items, key=lambda x: x['open_time'])
    results = []

    for i in range(len(sorted_items) - 1):
        current_item = sorted_items[i]
        next_item = sorted_items[i + 1]

        # 解析当前期号码并转换
        current_codes = list(map(int, current_item['open_code'].split(',')))
        converted_codes = convert_numbers(current_codes)
        converted_str = ",".join([f"{n:02d}" for n in converted_codes])

        # 解析下期实际号码
        next_codes = list(map(int, next_item['open_code'].split(',')))
        # 确保有足够的号码进行比较
        if len(next_codes) < 10:
            print(f"警告: 期号 {next_item['issue_no']} 的号码不足10个 ({len(next_codes)}个)")
            next_codes += [0] * (10 - len(next_codes))  # 不足部分补0
        next_codes = next_codes[:10]  # 取前10位
        next_str = ",".join([f"{n:02d}" for n in next_codes])

        # 找出中奖的号码及其位置
        winning_numbers = []
        for pos, (pred, actual) in enumerate(zip(converted_codes, next_codes)):
            if pred == actual:
                winning_numbers.append(f"{pred}({pos + 1})")

        winning_str = ",".join(winning_numbers) if winning_numbers else "无"

        # 正确统计中奖次数（位置匹配数）
        win_count = sum(1 for p, a in zip(converted_codes, next_codes) if p == a)

        results.append({
            "当前期期号": current_item['issue_no'],
            "当前期号码": current_item['open_code'],
            "转换后号码": converted_str,
            "下期期号": next_item['issue_no'],
            "下期实际号码": next_str,
            "中奖次数": win_count,
            "中奖号码": winning_str
        })

    # 计算当日总中奖次数
    total_wins = sum(r["中奖次数"] for r in results) if results else 0
    total_predictions = len(results)

    return {
        "results": results,
        "total_wins": total_wins,
        "total_predictions": total_predictions
    }

def analyze_lottery1(data, target_numbers,bet_config):
    results = []
    items = sorted(data, key=lambda x: x['open_time'])
       # 从第二期开始分析（因为第一期没有上一期数据）
    win_count = 0
    for i in range(1, len(items)):
        current_issue = items[i]
        current_open_code = current_issue['open_code']
        current_codes = current_open_code.split(',')

        # 获取上一期数据
        prev_issue = items[i - 1]
        prev_issue_no = prev_issue['issue_no']
        prev_open_code = prev_issue['open_code']
        prev_codes = prev_open_code.split(',')

        # 提取上一期关键号码的位置及对应的号码（位置从1开始）
        # 新增：记录每个位置对应的关键号码（用于匹配下注规则）
        positions_target = [
                {"pos": pos + 1, "code": code} 
                for pos, code in enumerate(prev_codes) 
                if code in target_numbers
            ]

        # 计算当前期的中奖情况
        win_positions = []
        win_codes = []

        # 关键修改：在当前期的相同位置，根据上一期的号码匹配对应下注规则
        for target in positions_target:
            pos = target["pos"]
            prev_code = target["code"]  # 上一期该位置出现的关键号码
            if 0 <= pos - 1 < len(current_codes):
                current_code = current_codes[pos - 1]
                # 按上一期号码对应的规则下注（01位置押01，02位置押02）
                if current_code in bet_config[prev_code]:
                    win_count += 1
                    win_positions.append(pos)
                    win_codes.append(current_code)
    total_predictions = len(results)
    return {
        "results": results,
        "total_wins": win_count,
        "total_predictions": total_predictions
    }

def analyze_lottery(daily_data, target_numbers,bet_config, strategy_config,counter_divisor):
    today = datetime.now().strftime("%Y-%m-%d")
    daily_results = {}
    # 计算总押注号码数（用于计算投注金额）
    total_bet_numbers = sum(len(codes) for codes in bet_config.values())
    for date, items in daily_data.items():
        date_str = date.strftime("%Y-%m-%d")
        print(f"分析日期: {date_str}，共 {len(items)} 期数据")
        if today != date_str:
            continue

        # 初始化不同中奖个数的计数器（1-10个）
        win_count_by_number = {i: 0 for i in range(1, 11)}  # 修改：从1开始统计

        daily_result = {
            'date': date_str,
            'total_issues': len(items),
            'win_count': 0,  # 中奖总次数（每个匹配的号码都算一次）
            'win_count_by_number': win_count_by_number,  # 按中奖个数统计的次数
            'bet_config': bet_config,
            'counter_data': [],
            'consecutive_bet_data': []  # 连续押注数据
        }

        # 从配置中获取参数
        initial_capital = strategy_config["initial_capital"]
        current_capital = initial_capital  # 当前本金
        payout_ratio = strategy_config["payout_ratio"]

        # 当日停止下注标记
        stop_betting_today = False

        # 连续投注跟踪变量
        remaining_bet_periods = 0  # 剩余连续投注期数（0表示不处于连续投注阶段）
        base_bet_amount = strategy_config["base_bet_amount"]  # 每个号码的下注金额
        trigger_next = False  # 标记下一期是否需要开始投注
        bet_round = 0  # 投注轮次
        current_round_won = False  # 当前轮是否已中奖

        # 从第二期开始分析（第一期无历史数据）
        for i in range(1, len(items)):
            current_issue = items[i]
            current_issue_no = current_issue['issue_no']
            current_open_code = current_issue['open_code']
            current_open_time = current_issue['open_time']
            current_codes = current_open_code.split(',')

            # 上一期数据
            prev_issue = items[i - 1]
            prev_issue_no = prev_issue['issue_no']
            prev_open_code = prev_issue['open_code']
            prev_codes = prev_open_code.split(',')

            # 提取上一期关键号码的位置
            positions_target = [
                {"pos": pos + 1, "code": code}
                for pos, code in enumerate(prev_codes)
                if code in target_numbers
            ]

            # 计算当前期中奖情况（支持多号码匹配）
            win_count = 0
            win_positions = []
            win_codes = []
            for target in positions_target:
                pos = target["pos"]
                prev_code = target["code"]
                if 0 <= pos - 1 < len(current_codes):
                    current_code = current_codes[pos - 1]
                    # 检查当前号码是否在押注列表中（支持多个号码）
                    if current_code in bet_config[prev_code]:
                        win_count += 1
                        win_positions.append(pos)
                        win_codes.append(current_code)

            # 统计不同中奖个数的次数（修改：从1开始统计）
            if 1 <= win_count <= 10:
                daily_result['win_count_by_number'][win_count] += 1

            # 更新累计数据
            daily_cumulative_issues = i  # 累计期数（从1开始）
            daily_cumulative_wins = daily_result['win_count'] + win_count  # 累计中奖数

            # 计数器计算（使用公共参数作为除数）
            counter = daily_cumulative_issues / counter_divisor - daily_cumulative_wins
            daily_result['counter_data'].append({
                'issue_no': current_issue_no,
                'daily_cumulative_issues': daily_cumulative_issues,
                'daily_cumulative_wins': daily_cumulative_wins,
                'counter': counter,
                'open_time': current_open_time
            })

            # 更新总中奖数
            daily_result['win_count'] += win_count

            # 下注逻辑
            previous_capital = current_capital  # 记录调整前的本金
            current_bet_amount = 0  # 当期总下注金额（单注金额×总押注号码数）
            current_profit = 0  # 当期盈利
            betting = False  # 是否处于投注状态
            round_ended = False  # 当前轮是否结束
            stopped_by_capital = False  # 是否因本金达到阈值停止下注
            stopped_by_insufficient_funds = False  # 是否因资金不足停止下注

            # 检查是否因本金达到阈值停止下注
            if current_capital > strategy_config["stop_capital_threshold"]:
                stop_betting_today = True
                stopped_by_capital = True

            # 执行连续投注（剩余期数>0时）
            if remaining_bet_periods > 0 and not stop_betting_today:
                # 检查本金是否足够支付当前投注（总金额=单注金额×总押注号码数）
                if can_afford_bet(current_capital, base_bet_amount, total_bet_numbers):
                    betting = True
                    current_bet_amount = base_bet_amount * total_bet_numbers  # 计算总投注金额
                    # 盈利计算公式：中奖个数×单注金额×赔率 - 总投注金额
                    current_profit = win_count * base_bet_amount * payout_ratio - current_bet_amount
                    current_capital += current_profit  # 更新本金

                    # 如果在投注期内中奖，停止本轮投注
                    if win_count > 0:
                        current_round_won = True
                        remaining_bet_periods = 0  # 剩余期数设为0，结束本轮
                        round_ended = True
                    else:
                        remaining_bet_periods -= 1  # 剩余期数减1
                else:
                    # 资金不足，停止当天投注
                    stop_betting_today = True
                    stopped_by_insufficient_funds = True

            # 检查是否需要开始新的连续投注（由上一期触发）
            elif trigger_next and not stop_betting_today:
                # 检查本金是否足够支付一组投注
                if can_afford_bet(current_capital, base_bet_amount, total_bet_numbers):
                    betting = True
                    bet_round += 1  # 开始新的一轮
                    current_round_won = False  # 重置轮次中奖状态

                    current_bet_amount = base_bet_amount * total_bet_numbers  # 计算总投注金额
                    current_profit = win_count * base_bet_amount * payout_ratio - current_bet_amount
                    current_capital += current_profit

                    remaining_bet_periods = strategy_config["consecutive_bet_periods"] - 1  # 剩余期数
                    trigger_next = False  # 重置触发标记

                    # 如果第一轮投注就中奖，立即结束本轮
                    if win_count > 0:
                        current_round_won = True
                        remaining_bet_periods = 0
                        round_ended = True
                else:
                    # 资金不足，停止当天投注
                    stop_betting_today = True
                    stopped_by_insufficient_funds = True
                    trigger_next = False  # 重置触发标记

            # 连续中奖统计
            current_streak = 1 if win_count > 0 else 0
            if daily_result['consecutive_bet_data']:
                last_bet = daily_result['consecutive_bet_data'][-1]
                current_streak = last_bet['current_streak'] + 1 if win_count > 0 else 0
            max_streak = max(
                [bet['current_streak'] for bet in daily_result['consecutive_bet_data']] + [current_streak]
            ) if daily_result['consecutive_bet_data'] else current_streak

            # 格式化下注位置（显示所有押注的号码）
            bet_pos_display = []
            for target in positions_target:
                pos = target["pos"]
                code = target["code"]
                bet_codes = bet_config[code]
                bet_pos_display.append(f"{pos}({'/'.join(bet_codes)})")

            # 记录当期数据
            daily_result['consecutive_bet_data'].append({
                'prev_issue_no': prev_issue_no,
                'current_issue_no': current_issue_no,
                'prev_open_code': prev_open_code,
                'bet_positions': ", ".join(bet_pos_display),
                'current_open_code': current_open_code,
                'win_count': win_count,
                'win_positions': win_positions,
                'win_codes': win_codes,
                'current_streak': current_streak,
                'max_streak': max_streak,
                'open_time': current_open_time,
                'daily_cumulative_issues': daily_cumulative_issues,
                'daily_cumulative_wins': daily_cumulative_wins,
                'counter': counter,
                'betting': betting,  # 是否在投注期
                'base_bet_amount': base_bet_amount,
                'total_bet_numbers': total_bet_numbers,  # 总押注号码数
                'bet_amount': current_bet_amount,
                'profit': current_profit,
                'previous_capital': previous_capital,
                'current_capital': current_capital,
                'remaining_bet_periods': remaining_bet_periods,
                'trigger_next': trigger_next,
                'win_in_current': win_count > 0,
                'bet_round': bet_round,
                'current_round_won': current_round_won,
                'round_ended': round_ended,
                'stop_betting_today': stop_betting_today,
                'stopped_by_capital': stopped_by_capital,
                'stopped_by_insufficient_funds': stopped_by_insufficient_funds
            })

            # 核心逻辑：当前期中奖个数不为0时，下一期开始新一轮投注
            if win_count > 0 and remaining_bet_periods == 0 and not stop_betting_today:
                # 检查本金是否足够支付下一组投注
                if can_afford_bet(current_capital, base_bet_amount, total_bet_numbers):
                    trigger_next = True  # 当前期中奖且不在投注期，下一期开始投注
                else:
                    trigger_next = False  # 资金不足，不触发投注
            else:
                trigger_next = False

        # 保存最大连胜次数
        daily_result['max_streak'] = max(
            [bet['max_streak'] for bet in daily_result['consecutive_bet_data']]
        ) if daily_result['consecutive_bet_data'] else 0

        # 计算当天总盈利
        if daily_result['consecutive_bet_data']:
            daily_result['daily_profit'] = daily_result['consecutive_bet_data'][-1]['current_capital'] - initial_capital
        else:
            daily_result['daily_profit'] = 0

        daily_results[date] = daily_result
    return daily_results


def generate_daily_html_report(date_str, analysis_data, output_dir):
    """生成单日HTML报告"""
    results = analysis_data["results"]
    if not results:
        return None

    # 生成表格行的HTML
    table_rows = ""
    for row in results:
        table_rows += f"""
        <tr>
            <td>{row["当前期期号"]}</td>
            <td>{row["当前期号码"]}</td>
            <td>{row["转换后号码"]}</td>
            <td>{row["下期期号"]}</td>
            <td>{row["下期实际号码"]}</td>
            <td class="win-count">{row["中奖次数"]}</td>
            <td class="winning-numbers">{row["中奖号码"]}</td>
        </tr>
        """

    # 完整HTML内容
    html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{date_str} 彩票中奖统计报告</title>
    <style>
        body {{ font-family: Arial, sans-serif; max-width: 100%; margin: 0 auto; padding: 15px; }}
        .page-header {{ text-align: center; margin-bottom: 20px; }}
        .stats-card {{ background-color: #f8f9fa; padding: 15px; margin-bottom: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
        .stats-title {{ font-size: 18px; font-weight: bold; margin-bottom: 10px; }}
        .stats-grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; }}
        .stat-item {{ background-color: white; padding: 12px; border-radius: 5px; border: 1px solid #e0e0e0; }}
        .stat-label {{ font-size: 14px; color: #666; margin-bottom: 5px; }}
        .stat-value {{ font-size: 20px; font-weight: bold; }}
        .section-toggle {{ 
            background-color: #f0f0f0; 
            padding: 12px 15px; 
            border-radius: 5px; 
            cursor: pointer; 
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }}
        .section-toggle:hover {{ background-color: #e8e8e8; }}
        .section-content {{ margin-bottom: 25px; }}
        .toggle-icon {{ transition: transform 0.3s ease; }}
        .collapsed .toggle-icon {{ transform: rotate(180deg); }}
        .collapsed + .section-content {{ display: none; }}
        .table-container {{ overflow-x: auto; -webkit-overflow-scrolling: touch; }}
        .lottery-table {{ width: 100%; min-width: 800px; border-collapse: collapse; }}
        .lottery-table th, .lottery-table td {{ 
            padding: 10px 8px; 
            border: 1px solid #e0e0e0; 
            text-align: center; 
            white-space: nowrap;
            font-size: 14px;
        }}
        .lottery-table th {{ 
            background-color: #f5f5f5; 
            font-weight: bold; 
            position: sticky; 
            top: 0; 
            z-index: 10;
        }}
        .win-count {{ color: #2ecc71; font-weight: bold; }}
        .winning-numbers {{ color: #e67e22; font-weight: bold; }}
        .footer-note {{ text-align: center; color: #666; margin-top: 20px; font-size: 13px; }}
        @media (max-width: 768px) {{
            .lottery-table th, .lottery-table td {{
                padding: 8px 5px;
                font-size: 13px;
            }}
            .stats-grid {{ grid-template-columns: 1fr; }}
        }}
    </style>
    <script>
        // 使用更兼容的DOM加载检测方法
        (function() {{
            // 确保DOM已加载完成
            function init() {{
                var toggles = document.querySelectorAll('.section-toggle');
                for (var i = 0; i < toggles.length; i++) {{
                    toggles[i].addEventListener('click', function() {{
                        this.classList.toggle('collapsed');
                    }});
                }}
            }}

            // 兼容各种浏览器的DOM加载检测
            if (document.readyState === 'complete' || 
                (document.readyState !== 'loading' && !document.documentElement.doScroll)) {{
                init();
            }} else {{
                document.addEventListener('DOMContentLoaded', init);
                window.addEventListener('load', init);
            }}
        }})();
    </script>
</head>
<body>
    <div class="page-header">
        <h1>{date_str} 彩票转换号码中奖统计</h1>
        <p>数据日期：{date_str}</p>
        <p>总记录数：{len(results)}</p>
    </div>

    <!-- 统计汇总模块 -->
    <div class="stats-card">
        <div class="stats-title">每日汇总统计</div>
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-label">总预测次数</div>
                <div class="stat-value">{analysis_data["total_predictions"]}</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">总中奖次数</div>
                <div class="stat-value win-count">{analysis_data["total_wins"]}</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">平均每期中奖次数</div>
                <div class="stat-value">{analysis_data["total_wins"] / analysis_data["total_predictions"]:.2f}</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">最高单期中奖次数</div>
                <div class="stat-value">{max(r["中奖次数"] for r in results) if results else 0}</div>
            </div>
        </div>
    </div>

    <!-- 可折叠的详细列表模块 -->
    <div class="section-toggle">
        <div class="toggle-title">点击查看/隐藏详细记录</div>
        <div class="toggle-icon">▼</div>
    </div>
    <div class="section-content">
        <div class="table-container">
            <table class="lottery-table">
                <thead>
                    <tr>
                        <th>当前期期号</th>
                        <th>当前期号码</th>
                        <th>转换后号码</th>
                        <th>下期期号</th>
                        <th>下期实际号码</th>
                        <th class="win-count">中奖次数</th>
                        <th class="winning-numbers">中奖号码(位置)</th>
                    </tr>
                </thead>
                <tbody>
                    {table_rows}
                </tbody>
            </table>
        </div>
    </div>

    <div class="footer-note">
        <p>生成时间：{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</p>
        <p>数据来源：merged_20250604_200045.json</p>
    </div>
</body>
</html>
    """

    output_filename = os.path.join(output_dir, f"{date_str}_lottery_report.html")
    with open(output_filename, 'w', encoding='utf-8') as f:
        f.write(html_content.strip())
    return output_filename


def analyze_lottery_data(dir_path,file_name,choose_number,jsq,cai_start,cai_end):
    # 配置路径（请根据实际路径修改）
    global CONVERSION_RULE,jsq1,COUNTER_DIVISOR,STRATEGY_CONFIG,cai_start1,cai_end1
    pairs = choose_number.split(',')
    BET_CONFIG = {}
    for pair in pairs:
        key, value = pair.split(':')
        if key in BET_CONFIG:
            BET_CONFIG[key].append(value)
        else:
            BET_CONFIG[key] = [value]
    TARGET_NUMBERS = list(BET_CONFIG.keys())
    jsq1 = float(jsq)
    COUNTER_DIVISOR = float(jsq)

    cai_start1 = cai_start
    cai_end1 = cai_end

    STRATEGY_CONFIG = {
        "initial_capital": 1000,  # 初始本金
         "consecutive_bet_periods": 50,  # 连续投注期数上限
         "base_bet_amount": 2,  # 单注金额（每个号码的投注金额）
         "payout_ratio": 9.7052,  # 赔率
         "stop_capital_threshold":100000 # 停止下注的本金阈值
         }

    today = datetime.now().strftime("%Y-%m-%d")
    full_path = os.path.join(dir_path, file_name)

    # 读取JSON数据
    try:
        with open(full_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except FileNotFoundError:
        print(f"错误：找不到JSON文件 - {full_path}")
        return
    except json.JSONDecodeError:
        print(f"错误：JSON文件格式不正确 - {full_path}")
        return
    filtered_items = [item for item in data.get('items', [])]
    seen_issues = {}
    unique_items = []
    # 先按open_time降序排序，确保每个issue_no只保留最新的一条
    for item in sorted(filtered_items, key=lambda x: x.get('open_time', ''), reverse=True):
        issue_no = item.get('issue_no')
        if issue_no and issue_no not in seen_issues:
            seen_issues[issue_no] = True
            unique_items.append(item)
    data = {"items": sorted(unique_items, key=lambda x: x.get('open_time', ''))}

    # 数据分组与分析
    daily_groups = group_data_by_date(data)


    daily_analysis_data = analyze_lottery(daily_groups,TARGET_NUMBERS,BET_CONFIG,STRATEGY_CONFIG,COUNTER_DIVISOR)
    for items in daily_analysis_data.items():
        daily_analysis = items[1]
        if daily_analysis["win_count"]:
            total_cnt = daily_analysis["total_issues"]
            total_hits = daily_analysis["win_count"]
            save_settings(total_cnt,total_hits)
            print(f"{total_cnt}------------->{total_hits}")

if __name__ == "__main__":
    current_date = datetime.now().strftime('%Y%m%d')
    save_dir = f"spider_car_data_{current_date}"
    analyze_lottery_data(save_dir,"merged_20250809_104305.json","01:01,01:06,02:02,02:07,03:03,03:08,04:04,04:09","2.5","9")